import Title from "./components/index_title";
import { history } from "umi";
import { Swiper, Toast } from "antd-mobile";
import styles from "./index.css";
import Draggable, { DraggableData } from "react-draggable";
import { Box1 } from "../components/index_box/chart_box1";
import { Box2 } from "../components/index_box/chart_box2";
import { Box3 } from "../components/index_box/chart_box3";
import { Box4 } from "../components/index_box/chart_box4";
import { Box5 } from "../components/index_box/chart_box5";
import { Box6 } from "../components/index_box/chart_box6";
import { Box7 } from "../components/index_box/chart_box7";
import { Box8 } from "../components/index_box/chart_box8";
import { Box9 } from "../components/index_box/chart_box9";
import { Box10 } from "../components/index_box/chart_box10";
import { Box11 } from "../components/index_box/chart_box11";
import { useEffect, useState } from "react";

class SequencePages {
  page1: string[]
  pages: string[][]
  max_length: number
  all: string[];
  constructor(page1: string[]) {
    this.page1 = page1
    this.all = []
    this.max_length = 6
    this.pages = []
  }
  init() {
    this.pages = new Proxy([this.page1], {
      set: (target, prop, value, Receiver) => {
        let v = null
        if (prop !== 'length') {
          v = new Proxy(value, {
            set: (target, prop, value, receiver) => {
              if (prop === 'length') {
                if (value === this.max_length) {
                  Receiver.push([])
                } else if (value > this.max_length) {
                  throw new Error('数组长度不得大于' + this.max_length)
                } else if (value === 0) {
                  const index = Receiver.findIndex((item: any) => item === receiver)
                  if (index !== -1)
                    Receiver.splice(index, 1)
                }
              }
              return Reflect.set(target, prop, value, receiver)
            }
          })
        }
        else
          v = value
        return Reflect.set(target, prop, v, Receiver)
      }
    })
    this.pages.push([])
    let page_index = 1
    this.all.forEach(item => {
      const page = this.pages[page_index]
      if (!this.page1.includes(item)) {
        if (page.length <= this.max_length) {
          page.push(item)
          if (page.length === this.max_length) {
            page_index++
          }
        }
      }
    })
  }
  removePgae1(targetIndex: number) {
    const page1 = this.pages[0]
    const deletedItem = page1[targetIndex]
    page1.splice(targetIndex, 1)
    const push_index = this.pages.findIndex((item, index) => index !== 0 && item.length < this.max_length)
    this.pages[push_index].push(deletedItem)
    return [...this.pages]
  }

  removeIntoPage1(pageIndex: number, targetIndex: number) {
    const page1 = this.pages[0]
    const targetPage = this.pages[pageIndex]
    if (page1.length >= this.max_length) {
      Toast.show('首页已满')
      return [...this.pages]
    }
    const deleted = targetPage[targetIndex]
    targetPage.splice(targetIndex, 1)
    page1.push(deleted)
    return [...this.pages]
  }

  removeInPage1(index1: number, index2: number) {
    const page1 = this.pages[0]
    const start = page1[index1]
    page1[index1] = page1[index2]
    page1[index2] = start
    return [...this.pages]
  }
}

const box_sequence: string[] = JSON.parse(localStorage.getItem('box_sequence') || '["box1", "box2", "box3", "box4", "box5", "box6"]')
const sequencePages = new SequencePages(box_sequence)

export default function Home() {
  let box_main_top = 0
  const [swiper_index, setSwiper_index] = useState(0)
  const [loadding, setLoadding] = useState(true)
  const [dragDisabled, setDragDisabled] = useState(true)
  const [render_box_sequence, setRender_box_sequence] = useState([[]] as string[][])
  const box_map = new Map([['box1', Box1], ['box2', Box2], ['box3', Box3], ['box4', Box4],
  ['box5', Box5], ['box6', Box6], ['box7', Box7], ['box8', Box8], ['box9', Box9], ['box10', Box10], ['box11', Box11]])
  let box_position: { left: number, top: number }[] = []
  let start_index = 0
  useEffect(() => {
    sequencePages.all = [...box_map.keys()]
    sequencePages.init()
    setRender_box_sequence(sequencePages.pages)
  }, [])
  useEffect(() => {
    const indexTitle = document.getElementById('index_title')
    box_main_top = indexTitle?.offsetHeight || 0
    const boxs = document.getElementsByClassName('react-draggable')
    box_position = [...boxs].map((item: any) => ({ left: item.offsetLeft, top: item.offsetTop }))
    setLoadding(false)
  })
  const render_box_page1 = function () {
    return render_box_sequence[0].map(item => {
      const Box = box_map.get(item)
      if (Box)
        return <Draggable
          onStart={onStart}
          onDrag={onMove}
          onStop={onEnd}
          position={{ x: 0, y: 0 }}
          key={item} disabled={dragDisabled}>
          <div onClick={() => dragDisabled && history.push('/' + item)}><Box></Box></div>
        </Draggable>
    })
  }
  const render_box_page_other = function (index: number) {
    return render_box_sequence[index]?.map((item, index) => {
      const Box = box_map.get(item)
      if (Box)
        return <div key={item} onClick={() => dragDisabled ? history.push('/' + item) : intoPage1(index)}><Box></Box></div>
    })
  }
  const onStart = (e: any, data: DraggableData) => {
    box_position.forEach((item, index) => {
      const { left, top } = item
      const targetLeft = data.node.offsetLeft - left
      const targetTop = data.node.offsetTop - top
      const m = targetLeft + targetTop
      if (m === 0) start_index = index
    })
  }
  const onMove = (e: any) => {
    if (e.changedTouches[0].pageY < box_main_top) {
      Toast.show('松开将在主页移除')
    }
  }
  const onEnd = (e: any, data: DraggableData) => {
    if (e.changedTouches[0].pageY < box_main_top) {
      const results = sequencePages!.removePgae1(start_index)
      return setRender_box_sequence(results)
    }
    let min = 99999
    let end_index = 0
    box_position.forEach((item, index) => {
      const { left, top } = item
      const targetLeft = data.node.offsetLeft + data.x - left
      const targetTop = data.node.offsetTop + data.y - top
      const m = targetLeft * targetLeft + targetTop * targetTop
      if (m < min) {
        min = m
        end_index = index
      }
    })
    const results = sequencePages!.removeInPage1(start_index, end_index)
    setRender_box_sequence(results)
  }
  const onChangeDragDisabled = () => {
    if (dragDisabled === false) localStorage.setItem('box_sequence', JSON.stringify(sequencePages?.page1))
    if (swiper_index !== 0 && dragDisabled) Toast.show('点击可移入主页')
    setDragDisabled((val) => !val)
  }
  const intoPage1 = (index: number) => {
    setRender_box_sequence(sequencePages!.removeIntoPage1(swiper_index, index))
  }
  const onIndexChange = (index: number) => {
    setSwiper_index(index)
  }
  return (
    <div className={styles.navs}>
      <div id="index_title">
        <Title></Title>
        {(!dragDisabled && swiper_index === 0) && <div className={styles.shadow}></div>}
      </div>
      <Swiper allowTouchMove={dragDisabled} onIndexChange={onIndexChange}>
        {render_box_sequence.map((item, index) =>
          <Swiper.Item key={index + 1}>
            {!loadding && (index === 0 ? <div className={styles.control}>
              <span onClick={onChangeDragDisabled}>
                {dragDisabled ? '管理' : '完成'}</span>
            </div> : <div className={styles.control} onClick={onChangeDragDisabled}>{dragDisabled ? '加入主页' : '完成'}</div>)}
            <div className={styles.outbox}>
              {index === 0 ? render_box_page1() : render_box_page_other(index)}
            </div>
          </Swiper.Item>
        )}
      </Swiper>
    </div>
  );
}
